<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >考试报名</el-breadcrumb-item
          >
          <el-breadcrumb-item :to="{ name: 'GradeList' }"
            >选择考试级别</el-breadcrumb-item
          >
          <el-breadcrumb-item :to="{ name: 'CheckEnroll' }"
            >选择考试项目</el-breadcrumb-item
          >
          <el-breadcrumb-item>填写报名信息</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="add_user_infor_content">
        <!-- 步骤条 -->
        <el-row type="flex" justify="center">
          <el-col :span="13">
            <div class="add_user_infor_steps">
              <div class="add_user_infor_steps_title">报名流程</div>
              <el-steps :active="2" finish-status="success" align-center>
                <el-step title="选择考试级别"></el-step>
                <el-step title="选择考试项目"></el-step>
                <el-step title="填写报名信息"></el-step>
                <el-step title="确认报名"></el-step>
                <el-step title="支付费用"></el-step>
              </el-steps>
            </div>
          </el-col>
        </el-row>
        <div
          v-for="item in dateCheckList"
          :key="item.value"
          :label="item.label"
        >
          <!-- 按钮栏 -->
          <el-row type="flex" justify="start" style="margin-bottom: 10px">
            <el-col :span="24" class="add_user_infor_card_item">
              <div class="add_user_infor_card_item_title">
                考试时间：{{ item.label }}
              </div>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="addUserBtn(item.value)"
                >添加报名</el-button
              >
              <div class="add_user_infor_card_item_tips">
                剩余名额：{{ item.remain_quantity }}
              </div>
            </el-col>
          </el-row>
          <!-- 数据列表 -->
          <el-row type="flex" justify="center">
            <el-col :span="24">
              <el-table
                :data="examineeInforData[item.value].examineeInforShow"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="考生姓名"
                  width="180"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="identity_number"
                  label="身份证号"
                  width="260"
                  align="center"
                ></el-table-column>

                <el-table-column label="考试项目" align="center">
                  <template>
                    <div>{{ enrollData.enroll_name }}</div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="height"
                  label="身高"
                  width="120"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="date"
                  label="考试日期"
                  width="240"
                  align="center"
                  :formatter="formatterDateFn"
                ></el-table-column>

                <el-table-column
                  label="操作"
                  width="140"
                  itemprop=""
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteExamineeBtn(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="24">
              <div class="add_user_infor_pagination">
                <el-pagination
                  @size-change="(val) => listSizeChange(val, item.value)"
                  @current-change="(val) => listCurrentChange(val, item.value)"
                  :current-page="examineeInforData[item.value].currentPage"
                  :page-sizes="examineeInforData[item.value].pageSizes"
                  :page-size="examineeInforData[item.value].pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="examineeInforData[item.value].total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-row>
    <!-- 添加考生弹框 -->
    <el-dialog
      title="添加报名"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="dialogClose"
    >
      <el-row type="flex" justify="start" style="margin-bottom: 10px">
        <el-col :span="3">
          <el-button type="primary" size="mini" @click="toAddExamineeBtn()"
            >管理考生</el-button
          >
        </el-col>
        <el-col :span="2">
          <div class="add_user_select_box">筛选:</div>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="checkedLevel"
            placeholder="请选择篮球等级"
            size="mini"
            @change="checkedLevelChange"
            :clearable="true"
          >
            <el-option
              v-for="item in levelList"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div v-if="addUserListData != undefined && addUserListData.length > 0">
        <el-row type="flex" justify="center">
          <el-col :span="24">
            <el-table
              :data="addUserListShow"
              ref="addUserList"
              border
              style="width: 100%"
              size="mini"
              max-height="600"
              @selection-change="dialogSelectionChange"
              :cell-style="cellStyleFn"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="name"
                label="考生姓名"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="identity_number"
                label="身份证号"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="height"
                label="身高"
                width="100"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="real_level"
                label="篮球等级"
                width="100"
                align="center"
                :formatter="formatterLevelFn"
              ></el-table-column>

              <el-table-column
                label="状态"
                width="160"
                align="center"
                :formatter="formatterCheckStudentFn"
              ></el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="24">
            <div class="add_user_infor_pagination">
              <el-pagination
                @size-change="dialogListSizeChange"
                @current-change="dialogListCurrentChange"
                :current-page="dialogCurrentPage"
                :page-sizes="dialogPageSizes"
                :page-size="dialogPageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="dialogTotal"
              >
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row v-else>
        <el-empty description="暂无可选考生"></el-empty>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="24">
          <div class="add_user_infor_dialog_btn">
            <el-button
              size="small"
              type="primary"
              @click="dialogAddBtn()"
              style="margin-right: 30px"
              >添加</el-button
            >
            <el-button size="small" type="danger" @click="dialogClose()"
              >取消</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 底部提交 -->
    <div class="add_user_infor_bottom">
      <el-button
        type="danger"
        size="mini"
        icon="iconfont icon-bg-save"
        class="save_btn"
        @click="submitBtn()"
        >提交</el-button
      >
      <el-button
        type="info"
        size="mini"
        icon="iconfont icon-w_fanhui"
        @click="backBtn()"
        >返回上一页</el-button
      >
    </div>
  </div>
</template>
<style src="../../assets/css/enroll/addUserInforList.css" scoped></style>

<script>
export default {
  name: "AddUserInforList",
  components: {},
  data() {
    return {
      enrollId: "", // 当前选择考试id
      enrollData: {
        enroll_name: "2022篮球协会青少年篮球技能考试",
      }, // 考试信息
      dateCheckList: [], // 可选时间列表数据
      dialogVisible: false, // 弹框显示
      addUserListData: [], // 学生列表数据
      addUserListShow: [], // 学生列表显示
      dialogCurrentPage: 1, // 当前页
      dialogPageSizes: [10, 20, 50, 100], // 可选页容量
      dialogPageSize: 10, // 当前页容量
      dialogTotal: 0, // 总条数
      dialogSelectList: [], // 已选列表
      dialogCheckDate: "", // 弹框选择时间段
      examineeInforData: {}, // 报名总数据
      loadingKey: false,
      loadingText: "",
      levelList: [], // 等级列表
      checkedLevel: "", // 等级选择
    };
  },
  created: function () {
    let enrollId = this.$route.params.enrollId;
    if (enrollId != undefined && enrollId != "") {
      this.$store.commit("set_checkedEnrollId", enrollId);
      this.enrollId = enrollId;
    } else {
      this.enrollId = this.$store.state.checkedEnrollId;
    }
    this.getTimeListFn();
    this.getLevelListFn();
  },
  methods: {
    // 获取等级列表
    getLevelListFn: function () {
      let that = this;
      let url = "/mobile/levelText";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            let list = [
              {
                key: 0,
                value: "无",
              },
            ];
            response.level_list.forEach(function (item) {
              let obj = {
                key: item.level,
                value: item.title,
              };
              list.push(obj);
            });
            that.levelList = list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 查询考试时间
    getTimeListFn: function () {
      let that = this;
      let url = "/mobile/examtimeList";
      let data = {
        exam_id: this.enrollId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          if (response.code == 0) {
            that.enrollData.enroll_name = response.exam_info.title;
            let list = [];
            let setKey = false;
            if (JSON.stringify(that.$store.state.examineeInforList) != "{}") {
              setKey = true;
              var setData = that.$store.state.examineeInforList;
            }
            response.exam_times.forEach(function (item) {
              let obj = {
                value: item.id,
                label:
                  response.exam_info.exam_date + " " + item.exam_time_start,
                // + "-" + item.exam_time_end,
                remain_quantity: item.remain_quantity,
              };
              list.push(obj);
              let student = {};
              if (setKey && setData[item.id]) {
                student = {
                  value: item.id,
                  examineeInforShow: [], // 报名显示数据
                  examineeInforList: setData[item.id], // 报名列表数据
                  currentPage: 1, // 当前页
                  pageSizes: [10, 20, 50, 100], // 可选页容量
                  pageSize: 10, // 当前页容量
                  total: 0, // 总条数
                };
              } else {
                student = {
                  value: item.id,
                  examineeInforShow: [], // 报名显示数据
                  examineeInforList: [], // 报名列表数据
                  currentPage: 1, // 当前页
                  pageSizes: [10, 20, 50, 100], // 可选页容量
                  pageSize: 10, // 当前页容量
                  total: 0, // 总条数
                };
              }
              that.examineeInforData[item.id] = student;
              if (setKey) {
                that.setShowListFn(item.id);
              }
            });
            that.dateCheckList = list;
            that.getUserListDataFn();
          } else {
            that.loadingKey = false;
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 查询列表数据
    getUserListDataFn: function () {
      let that = this;
      let url = "/mobile/selectExamStudents";
      let data = {
        exam_id: this.enrollId,
        level: this.checkedLevel,
      };
      return new Promise(function (resolve, reject) {
        that.loadingText = "加载中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              let setKey = false;
              let setData = {};
              if (JSON.stringify(that.$store.state.examineeInforList) != "{}") {
                setKey = true;
                setData = that.$store.state.examineeInforList;
              }
              if (setKey) {
                let list = response.stu_infos;
                let remove = [];
                for (let item in setData) {
                  if (setData[item].length > 0) {
                    remove = remove.concat(setData[item]);
                  }
                }
                remove.forEach(function (item) {
                  let removeKey = list.findIndex((i) => i.id == item.id);
                  if (removeKey != -1) {
                    list.splice(removeKey, 1);
                  }
                });
                that.addUserListData = list;
                that.dialogTotal = list.length;
              } else {
                that.addUserListData = response.stu_infos;
                that.dialogTotal = response.total_count;
              }
              resolve(true);
            } else {
              that.$message.error(response.msg);
              resolve(false);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            reject(error);
          });
      });
    },
    // 移除考生
    deleteExamineeBtn: function (index, row) {
      let key = row.date;
      let indexData = this.examineeInforData[key].examineeInforList.findIndex(
        (i) => i.id == row.id
      );
      let obj = row;
      this.addUserListData.unshift(obj);
      this.examineeInforData[key].examineeInforList.splice(indexData, 1);
      this.setShowListFn(key);
    },
    // 页容量改变
    listSizeChange: function (val, key) {
      this.examineeInforData[key].currentPage = 1;
      this.examineeInforData[key].pageSize = val;
      this.setShowListFn(key);
    },
    // 当前页改变
    listCurrentChange: function (val, key) {
      this.examineeInforData[key].currentPage = val;
      this.setShowListFn(key);
    },
    // 设置列表显示数据
    setShowListFn: function (key) {
      let page =
        this.examineeInforData[key].currentPage == 0
          ? 1
          : this.examineeInforData[key].currentPage;
      let size = this.examineeInforData[key].pageSize;
      let start = (page - 1) * size;
      let end = page * size;
      let list = [];
      this.examineeInforData[key].total =
        this.examineeInforData[key].examineeInforList.length;
      if (start == this.examineeInforData[key].total) {
        page = page - 1;
        this.examineeInforData[key].currentPage = page;
        start = (page - 1) * size;
        end = page * size;
      }

      for (let i = start; i < end; i++) {
        if (this.examineeInforData[key].examineeInforList[i]) {
          list.push(this.examineeInforData[key].examineeInforList[i]);
        }
      }
      this.examineeInforData[key].examineeInforShow = list;
    },
    // 关闭弹窗
    dialogClose: function () {
      this.dialogVisible = false;
    },
    // 打开弹窗
    dialogOpen: function () {
      this.dialogVisible = true;
    },
    // 添加报名
    addUserBtn: function (key) {
      this.dialogCheckDate = key;
      this.dialogCurrentPage = 1;
      this.dialogPageSize = 10;
      this.setDialogShowListFn();
      this.dialogOpen();
    },
    // 弹框页容量改变
    dialogListSizeChange: function (val) {
      this.dialogCurrentPage = 1;
      this.dialogPageSize = val;
      this.setDialogShowListFn();
    },
    // 弹框当前页改变
    dialogListCurrentChange: function (val) {
      this.dialogCurrentPage = val;
      this.setDialogShowListFn();
    },
    // 弹框列表选择改变
    dialogSelectionChange: function (val) {
      this.dialogSelectList = val;
    },
    // 设置弹框列表显示数据
    setDialogShowListFn: function () {
      let page = this.dialogCurrentPage == 0 ? 1 : this.dialogCurrentPage;
      let size = this.dialogPageSize;
      let start = (page - 1) * size;
      let end = page * size;
      let list = [];
      this.dialogTotal = this.addUserListData.length;
      if (start == this.dialogTotal) {
        page = page - 1;
        this.dialogCurrentPage = page;
        start = (page - 1) * size;
        end = page * size;
      }

      for (let i = start; i < end; i++) {
        if (this.addUserListData[i]) {
          list.push(this.addUserListData[i]);
        }
      }
      this.loadingKey = false;
      this.addUserListShow = list;
    },
    // 弹窗确认添加
    dialogAddBtn: function () {
      let that = this;
      let key = this.dialogCheckDate;
      let maxIndex = this.dateCheckList.findIndex((i) => i.value == key);
      let maxNum = this.dateCheckList[maxIndex].remain_quantity;
      let addKey = 0;
      // 判断是否存在不合规用户
      for (let i = 0; i < this.dialogSelectList.length; i++) {
        let dataItem = this.dialogSelectList[i];
        if (dataItem.enrolled == 2) {
          addKey = 1;
          break;
        } else {
          if (
            dataItem.person_photo == "" ||
            dataItem.person_photo == null ||
            dataItem.person_photo == undefined
          ) {
            addKey = 2;
            break;
          }
        }
      }
      if (addKey == 1) {
        this.$message.error("选择的考生中存在已报名的考生");
      } else if (addKey == 2) {
        this.$message.error("选择的考生中存在未完善信息的考生");
      } else {
        if (
          this.dialogSelectList.length +
            that.examineeInforData[key].examineeInforList.length >
          maxNum
        ) {
          this.$message.error("选择考生数量超出该时段所剩名额数量");
        } else {
          this.dialogSelectList.forEach(function (item) {
            let index = that.examineeInforData[key].examineeInforList.findIndex(
              (i) => i.id == item.id
            );
            if (index == -1) {
              let obj = JSON.parse(JSON.stringify(item));
              obj.date = key;
              that.examineeInforData[key].examineeInforList.push(obj);
            }
            let removeIndex = that.addUserListData.findIndex(
              (j) => j.id == item.id
            );
            that.addUserListData.splice(removeIndex, 1);
          });
          that.dialogClose();
          that.dialogSelectList = [];
          that.setShowListFn(key);
        }
      }
    },
    // 管理考生
    toAddExamineeBtn: function () {
      let that = this;
      let examineeInforList = {};
      this.dateCheckList.forEach(function (item) {
        examineeInforList[item.value] =
          that.examineeInforData[item.value].examineeInforList;
      });
      this.$store.commit("set_examineeInforList", examineeInforList);
      this.$router.push({
        name: "ExamineeList",
      });
    },
    // 等级筛选
    checkedLevelChange: function (val) {
      let that = this;
      this.checkedLevel = val;
      this.dialogCurrentPage = 1;
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.getUserListDataFn()
        .then(function (res) {
          if (res) {
            that.loadingKey = true;
            that.setDialogShowListFn();
          } else {
            that.loadingKey = false;
            that.$message.error("网络繁忙,请稍后再试!");
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          that.$message.error(error);
        });
    },
    // 返回上一页
    backBtn: function () {
      this.$router.go(-1);
    },
    // 提交保存
    submitBtn: function () {
      let that = this;
      let examineeInforList = {};
      this.dateCheckList.forEach(function (item) {
        examineeInforList[item.value] =
          that.examineeInforData[item.value].examineeInforList;
      });
      let list = [];
      for (let item in examineeInforList) {
        if (examineeInforList[item].length > 0) {
          list = list.concat(examineeInforList[item]);
        }
      }
      if (list.length == 0) {
        that.$message.error("请先添加报名信息");
      } else {
        this.$store.commit("set_examineeInforList", examineeInforList);
        this.$router.push({
          name: "ConfirmOrder",
        });
      }
    },
    // 考试时间格式化
    formatterDateFn: function (row) {
      let date = row.date;
      let text = "";
      this.dateCheckList.forEach(function (item) {
        if (item.value == date) {
          text = item.label;
        }
      });
      return text;
    },
    // 学生可选状态格式化
    formatterCheckStudentFn: function (row) {
      let person_photo = row.person_photo;
      let enrolled = row.enrolled;
      let text = "";
      if (enrolled != 1) {
        text = "已报名";
      } else {
        if (
          person_photo == "" ||
          person_photo == null ||
          person_photo == undefined
        ) {
          text = "未完善信息";
        } else {
          text = "可报名";
        }
      }
      return text;
    },
    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 5) {
        if (row.enrolled == 2) {
          style = "color: #F6705E";
        } else {
          if (
            row.person_photo == "" ||
            row.person_photo == null ||
            row.person_photo == undefined
          ) {
            style = "color: #F6705E";
          } else {
            style = "color: #8ECF5F";
          }
        }
      }
      return style;
    },
    // 考试时间格式化
    formatterLevelFn: function (row) {
      let real_level = row.real_level;
      let text = "";
      this.levelList.forEach(function (item) {
        if (item.key == real_level) {
          text = item.value;
        }
      });
      return text;
    },
  },
};
</script>
